package app1.rapidsquare.com.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import app1.rapidsquare.com.activity.MainActivity;
import app1.rapidsquare.com.activity.WebViewActivity;
import app1.rapidsquare.com.adapter.AgileFragmentPagerAdapter;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.activity.R;
import app1.rapidsquare.com.core.Facebook;
import app1.rapidsquare.com.core.GooglePlus;
import app1.rapidsquare.com.core.ILoadComplete;
import app1.rapidsquare.com.database.AgileUserProvider;

public class ProfileFragment extends AgileFragment implements ILoadComplete {

    private Picasso picasso;
    private ImageView imageViewPhoto, mImageViewClearGooglePlus, mImageViewClearLinkedIn, mImageViewClearFacebook;
    private EditText editTextFirstName, editTextLastName, editTextPhone,
            editTextTitle, editTextCompany, editTextWebsite, editTextCity,
            editTextState, editTextMemo;

    private TextView mTextViewGooglePlusName, mTextViewLinkedInName, mTextViewFacebookName;
    private EditText editTextEmail;
    private RelativeLayout mRelativeLayoutGooglePlus, mRelativeLayoutLinkedIn, mRelativeLayoutFacebook;
    private Facebook mFacebook;
    private GooglePlus mGooglePlus;
    private ProgressBar mProgressBarGooglePlus, mProgressBarLinkedIn, mProgressBarFacebook, mProgressBarImageLoad;
    private User mCurrentUser;
    private String mPhotoUrl;


    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        setHasOptionsMenu(true);
        mFacebook = new Facebook(getActivity(), true, this);
        mFacebook.onCreate(savedInstanceState);
        mGooglePlus = new GooglePlus(getActivity(), true, this);
        mGooglePlus.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        mFacebook.onResume();
        mGooglePlus.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mFacebook.onPause();
        mGooglePlus.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mFacebook.onStop();
        mGooglePlus.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mFacebook.onDestroy();
        mGooglePlus.onDestroy();
        picasso.with(getActivity()).cancelRequest(targetImageView);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_profile, container, false);

        imageViewPhoto = (ImageView) v.findViewById(R.id.imageViewPicture);
        imageViewPhoto.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                SelectPhoto();
            }
        });

        editTextFirstName = (EditText) v.findViewById(R.id.editTextFirstName);
        editTextLastName = (EditText) v.findViewById(R.id.editTextLastName);
        editTextEmail = (EditText) v.findViewById(R.id.editTextEmail);
        editTextPhone = (EditText) v.findViewById(R.id.editTextPhone);

        editTextTitle = (EditText) v.findViewById(R.id.editTextTitle);
        editTextCompany = (EditText) v.findViewById(R.id.editTextCompany);
        editTextWebsite = (EditText) v.findViewById(R.id.editTextWebsite);
        editTextCity = (EditText) v.findViewById(R.id.editTextCity);
        editTextState = (EditText) v.findViewById(R.id.editTextState);
        editTextMemo = (EditText) v.findViewById(R.id.editTextMemo);

        picasso = Picasso.with(getActivity());

        mRelativeLayoutGooglePlus = (RelativeLayout) v.findViewById(R.id.relativeLayoutGooglePlus);

        mRelativeLayoutGooglePlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentUser == null || Utility.isNullOrEmpty(mCurrentUser.GooglePlusId) || mCurrentUser.GooglePlusName.equals("null")) {
                    mProgressBarGooglePlus.setVisibility(View.VISIBLE);
                    mRelativeLayoutGooglePlus.setEnabled(false);
                    mGooglePlus.RunGooglePlusLogin();
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://plus.google.com/" + mCurrentUser.GooglePlusId));
                    getActivity().startActivity(intent);
                }
            }
        });

        mRelativeLayoutLinkedIn = (RelativeLayout) v.findViewById(R.id.relativeLayoutLinkedIn);

        mRelativeLayoutLinkedIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentUser == null || Utility.isNullOrEmpty(mCurrentUser.LinkedInId) || mCurrentUser.LinkedInId.equals("null")) {
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    startActivityForResult(intent, Utility.SOCIAL_NAME_ACTIVITY_REQUEST_CODE);
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mCurrentUser.LinkedInId));
                    getActivity().startActivity(intent);
                }
            }
        });
        mRelativeLayoutFacebook = (RelativeLayout) v.findViewById(R.id.relativeLayoutFacebook);
        mRelativeLayoutFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentUser == null || Utility.isNullOrEmpty(mCurrentUser.FacebookId) || mCurrentUser.FacebookId.equals("null")) {
                    mProgressBarFacebook.setVisibility(View.VISIBLE);
                    mRelativeLayoutFacebook.setEnabled(false);
                    mFacebook.RunFacebookLogin();
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + mCurrentUser.FacebookId));
                    getActivity().startActivity(intent);
                }
            }
        });

        mTextViewGooglePlusName = (TextView) v.findViewById(R.id.textViewGooglePlusName);
        mTextViewLinkedInName = (TextView) v.findViewById(R.id.textViewLinkedInName);
        mTextViewFacebookName = (TextView) v.findViewById(R.id.textViewFacebookName);

        mImageViewClearGooglePlus = (ImageView) v.findViewById(R.id.imageViewClearGooglePlus);
        mImageViewClearGooglePlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentUser != null) {
                    mCurrentUser.GooglePlusId = "";
                    mCurrentUser.GooglePlusName = "";
                    LoadSocialData(mCurrentUser);
                }
            }
        });
        mImageViewClearLinkedIn = (ImageView) v.findViewById(R.id.imageViewClearLinkedIn);
        mImageViewClearLinkedIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentUser != null) {
                    mCurrentUser.LinkedInId = "";
                    mCurrentUser.LinkedInName = "";
                    LoadSocialData(mCurrentUser);
                }
            }
        });
        mImageViewClearFacebook = (ImageView) v.findViewById(R.id.imageViewClearFacebook);
        mImageViewClearFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentUser != null) {
                    mCurrentUser.FacebookId = "";
                    mCurrentUser.FacebookName = "";
                    LoadSocialData(mCurrentUser);
                }
            }
        });
        mProgressBarGooglePlus = (ProgressBar) v.findViewById(R.id.progressBarGooglePlus);
        mProgressBarLinkedIn = (ProgressBar) v.findViewById(R.id.progressBarLinkedIn);
        mProgressBarFacebook = (ProgressBar) v.findViewById(R.id.progressBarFacebook);
        mProgressBarImageLoad = (ProgressBar) v.findViewById(R.id.progressBarImageLoad);


        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        editTextPhone.addTextChangedListener(new TextWatcher() {
            private boolean mFormatting;
            private int mAfter;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int after) {
                mAfter = after;
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!mFormatting) {
                    mFormatting = true;
                    if (mAfter > 0) {
                        editTextPhone.setText(formatPhoneNumber(editable.toString().trim()));

                        editTextPhone.setSelection(editTextPhone.getText().length());
                    }

                    mFormatting = false;
                }
            }
        });

        User userSession = Utility.getUserSession(getActivity());

        AgileUserProvider userProvider = new AgileUserProvider(getActivity());
        mCurrentUser = userProvider.SelectById(userSession.Id);
        if (mCurrentUser == null)
            mCurrentUser = userSession;

        if (savedInstanceState != null && savedInstanceState.containsKey(Utility.PROFILE_DATA_SAVEDINSTANCESTATE)) {
            User userFromSocial = (User) savedInstanceState.getSerializable(Utility.PROFILE_DATA_SAVEDINSTANCESTATE);
            if (mCurrentUser == null)
                mCurrentUser = userFromSocial;
            else
                mCurrentUser = MergeUserData(mCurrentUser, userFromSocial);
        }

        if (savedInstanceState != null && savedInstanceState.containsKey(Utility.PROFILE_DATA_IMAGE_SAVEDINSTANCESTATE)) {
            mCurrentUser.ImageUrl = savedInstanceState.getString(Utility.PROFILE_DATA_IMAGE_SAVEDINSTANCESTATE);
        }

        LoadUserProfile(mCurrentUser);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8080 && resultCode == Activity.RESULT_OK) {
            TakePhotoOnCamera();
        }
        if (requestCode == 8081 && resultCode == Activity.RESULT_OK && data != null) {
            ChoseFromGallery(data);
        }
        if (requestCode == Utility.SOCIAL_NAME_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
            User user = (User) data.getSerializableExtra(Utility.LINKED_IN_INTENT_DATA_NAME);
            LoadSocialData(user);
        }

        if (data != null)
            mFacebook.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Utility.GOOGLE_PLUS_REQUEST_CODE) {
            mGooglePlus.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.profile, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.save) {
            if (IsAvailableInternet())
                validate();
            else
                ((MainActivity) getActivity()).mTextViewInternetConnection.setVisibility(View.VISIBLE);
        }
        return super.onOptionsItemSelected(item);
    }

    private void SelectPhoto() {
        final CharSequence[] options = {"Clear photo", "Take from camera", "Select from gallery"};

        AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity());

        builder.setTitle("Add Photo!");

        builder.setItems(options, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int item) {

                if (options[item].equals("Clear photo")) {
                    ClearPhoto();
                }

                if (options[item].equals("Take from camera")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                    if (isSDPresent) {
                        File f = new File(android.os.Environment
                                .getExternalStorageDirectory(), "cameraphoto.png");

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

                        startActivityForResult(intent, 8080);
                    } else
                        Toast.makeText(getActivity(), getResources().getString(R.string.external_storage_card_is_not_available), Toast.LENGTH_SHORT).show();

                } else if (options[item].equals("Select from gallery")) {

                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(intent, 8081);
                }
            }
        });

        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.show();
    }

    private void TakePhotoOnCamera() {
       /* File f = new File(Environment.getExternalStorageDirectory()
                + File.separator);
        for (File temp : f.listFiles()) {
            if (temp.getName().equals("cameraphoto.png")) {
                f = temp;
                break;
            }
        }*/
        try {
           /* Bitmap bitmap;

            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

            bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

                    bitmapOptions);

            String path = android.os.Environment

                    .getExternalStorageDirectory()

                    + File.separator;

            f.delete();

            OutputStream outFile = null;

            String ImagePath = path + String.valueOf(System.currentTimeMillis())
                    + ".png";
            File file = new File(ImagePath);

            outFile = new FileOutputStream(file);

            bitmap.compress(Bitmap.CompressFormat.PNG, 85, outFile);

            outFile.flush();

            outFile.close();*/
            Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
            if (isSDPresent) {
                File f = new File(android.os.Environment
                        .getExternalStorageDirectory(), "cameraphoto.png");
                if (f != null && f.exists()) {
                    picasso.load(f)
                            .placeholder(R.drawable.add_photo)
                            .skipMemoryCache()
                            .error(R.drawable.add_photo)
                            .resizeDimen(R.dimen.image_size,
                                    R.dimen.image_size).centerInside()
                            .into(targetImageView);
                }

            } else
                Toast.makeText(getActivity(), getResources().getString(R.string.external_storage_card_is_not_available), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Utility.Log("ProfileFragment -> TakePhotoOnCamera ", e);
        }
    }

    private void ChoseFromGallery(Intent data) {
        Uri selectedImage = data.getData();

        String[] filePath = {MediaStore.Images.Media.DATA};

        Cursor c = getActivity().getContentResolver().query(
                selectedImage, filePath, null, null, null);

        c.moveToFirst();

        int columnIndex = c.getColumnIndex(filePath[0]);

        String resourceId = c.getString(columnIndex);

        c.close();

        if (!Utility.isNullOrEmpty(resourceId)) {
            File file = new File(resourceId);
            if (file != null && file.exists()) {
                picasso.load(file)
                        .placeholder(R.drawable.add_photo)
                        .skipMemoryCache()
                        .error(R.drawable.add_photo)
                        .resizeDimen(R.dimen.image_size,
                                R.dimen.image_size).centerInside()
                        .into(targetImageView);
            }
        } else {
            Toast.makeText(getActivity(), getResources().getString(R.string.galary_is_not_available), Toast.LENGTH_SHORT).show();
        }
    }

    private void validate() {

        if (Utility.isNullOrEmpty(editTextFirstName.getText().toString())) {
            Toast.makeText(getActivity(), getResources().getString(R.string.first_name_is_empty), Toast.LENGTH_SHORT).show();
            return;
        }
        if (Utility.isNullOrEmpty(editTextLastName.getText().toString())) {
            Toast.makeText(getActivity(), getResources().getString(R.string.last_name_is_empty), Toast.LENGTH_SHORT).show();
            return;
        }

        if (Utility.isNullOrEmpty(editTextEmail.getText().toString())) {
            Toast.makeText(getActivity(), getResources().getString(R.string.email_is_empty), Toast.LENGTH_SHORT).show();
            return;
        }

        String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

        if (!editTextEmail.getText().toString().matches(emailPattern)) {
            Toast.makeText(getActivity(), getResources().getString(R.string.validation_valid_email), Toast.LENGTH_SHORT).show();
            return;
        }


        User userSession = Utility.getUserSession(getActivity());
        if (userSession != null) {
            if (!editTextEmail.getText().toString().equals(userSession.Email))
                CheckEmail();
            else
                SaveUserProfile();
        }
    }

    private void SaveUserProfile() {

        User userDetails = mCurrentUser;
        try {
            if (userDetails == null)
                userDetails = new User();

            userDetails.UserToken = Utility.getUserSession(getActivity()).UserToken;
            userDetails.Email = editTextEmail.getText().toString().trim();
            userDetails.FirstName = editTextFirstName.getText().toString().trim();
            userDetails.Password = Utility.getUserSession(getActivity()).Password;
            userDetails.LastName = editTextLastName.getText().toString().trim();

            String removerWhiteSpacePattern = "(\\w)(\\s+)([\\.,])";
            String phoneNumber = editTextPhone.getText().toString().trim();
            phoneNumber = phoneNumber.replace("(", "");
            phoneNumber = phoneNumber.replace(")", "");
            phoneNumber = phoneNumber.replace("-", "");
            phoneNumber = phoneNumber.replace("*", "");
            phoneNumber = phoneNumber.replace("#", "");
            phoneNumber = phoneNumber.replace("+", "");
            phoneNumber = phoneNumber.replaceAll(removerWhiteSpacePattern, "");

            userDetails.Phone = phoneNumber;
            userDetails.Title = editTextTitle.getText().toString().trim();
            userDetails.Company = editTextCompany.getText().toString().trim();
            userDetails.Site = editTextWebsite.getText().toString().trim();
            userDetails.City = editTextCity.getText().toString().trim();
            userDetails.State = editTextState.getText().toString().trim();
            userDetails.Info = editTextMemo.getText().toString().trim();
            userDetails.AdditionalInfo = "";

            if (Utility.isNullOrEmpty(userDetails.FacebookId) || userDetails.FacebookId.equals("null"))
                userDetails.FacebookId = "";
            if (Utility.isNullOrEmpty(userDetails.FacebookName) || userDetails.FacebookName.equals("null"))
                userDetails.FacebookName = "";
            if (Utility.isNullOrEmpty(userDetails.LinkedInId) || userDetails.LinkedInId.equals("null"))
                userDetails.LinkedInId = "";
            if (Utility.isNullOrEmpty(userDetails.LinkedInName) || userDetails.LinkedInName.equals("null"))
                userDetails.LinkedInName = "";
            if (Utility.isNullOrEmpty(userDetails.GooglePlusId) || userDetails.GooglePlusId.equals("null"))
                userDetails.GooglePlusId = "";
            if (Utility.isNullOrEmpty(userDetails.GooglePlusName) || userDetails.GooglePlusName.equals("null"))
                userDetails.GooglePlusName = "";

            Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
            if (isSDPresent) {
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "temp.png");
                if (file.exists()) {
                    Utility.UploadImage(getActivity(), file);
                }
            }

            String jsonResult = Utility.Serialize(userDetails).toString();

            this.mHttpEntity = new StringEntity(jsonResult, "utf-8");
            this.mHttpEntity.setContentType("application/json;charset=UTF-8");
            this.mHttpEntity.setContentEncoding(new BasicHeader(
                    HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

            setUrl(Utility.SET_USER_URL);
            setRequestMethodType(Utility.RequestMethodType.POST);
            SendRequest(true);

        } catch (Exception e) {
            Utility.Log("ProfileFragment -> SaveUserProfile ", e);
        }
    }

    @Override
    protected void getResponce(String jsonResult) {
        if (!Utility.isNullOrEmpty(jsonResult)) {
            try {
                JSONObject jObject = new JSONObject(jsonResult);
                String result = jObject.getString("Result");
                if (result.equals("True")) {

                    User userSession = Utility.getUserSession(getActivity());
                    if (userSession != null) {
                        userSession.Email = editTextEmail.getText().toString();
                        Utility.setUserSession(getActivity(), userSession);
                    }

                    Utility.AgileSyncUpdater(new AgileUserProvider(getActivity()), this);

                    AgileFragmentPagerAdapter fragmentPagerAdapter = ((MainActivity) getActivity()).mFragmentPagerAdapter;
                    int schedulePosition = fragmentPagerAdapter.getPosition(EventFragment.class);
                    if (schedulePosition == -1)
                        schedulePosition = 3;
                    ((MainActivity) getActivity()).mViewPager.setCurrentItem(schedulePosition);
                }

            } catch (Exception ex) {
                Utility.Log("ProfileFragment -> getResponce ", ex);
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mFacebook.onSaveInstanceState(outState);
        mGooglePlus.onSaveInstanceState(outState);

        if (outState != null) {
            outState.putSerializable(Utility.PROFILE_DATA_SAVEDINSTANCESTATE, mCurrentUser);
            if (!Utility.isNullOrEmpty(mPhotoUrl))
                outState.putString(Utility.PROFILE_DATA_IMAGE_SAVEDINSTANCESTATE, mPhotoUrl);
        }
    }

    private void LoadUserProfile(User profileData) {
        if (profileData != null) {

            LoadPhoto(profileData.ImageUrl);

            if (!Utility.isNullOrEmpty(profileData.FirstName) && !profileData.FirstName.equals("null"))
                editTextFirstName.setText(profileData.FirstName);
            if (!Utility.isNullOrEmpty(profileData.LastName) && !profileData.LastName.equals("null"))
                editTextLastName.setText(profileData.LastName);
            if (!Utility.isNullOrEmpty(profileData.Email) && !profileData.Email.equals("null"))
                editTextEmail.setText(profileData.Email);
            if (!Utility.isNullOrEmpty(profileData.Phone) && !profileData.Phone.equals("null"))
                editTextPhone.setText(profileData.Phone);
            if (!Utility.isNullOrEmpty(profileData.Title) && !profileData.Title.equals("null"))
                editTextTitle.setText(profileData.Title);
            if (!Utility.isNullOrEmpty(profileData.Company) && !profileData.Company.equals("null"))
                editTextCompany.setText(profileData.Company);
            if (!Utility.isNullOrEmpty(profileData.Site) && !profileData.Site.equals("null"))
                editTextWebsite.setText(profileData.Site);
            if (!Utility.isNullOrEmpty(profileData.City) && !profileData.City.equals("null"))
                editTextCity.setText(profileData.City);
            if (!Utility.isNullOrEmpty(profileData.State) && !profileData.State.equals("null"))
                editTextState.setText(profileData.State);
            if (!Utility.isNullOrEmpty(profileData.Info) && !profileData.Info.equals("null"))
                editTextMemo.setText(profileData.Info);
        }

        LoadSocialData(profileData);
    }

    private void LoadPhoto(final String fileName) {
        User userSession = Utility.getUserSession(getActivity());
        final String photoUrl = Utility.IMAGE_URL + "?Code="
                + userSession.Code;

        new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(Void... voids) {
                try {
                    URL mUrl = new URL(photoUrl);
                    HttpURLConnection connection;

                    if (mUrl.getProtocol().toLowerCase().equals("https")) {
                        Utility.trustAllHosts();
                        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) mUrl.openConnection();
                        httpsURLConnection.setHostnameVerifier(Utility.DO_NOT_VERIFY);
                        connection = httpsURLConnection;
                    } else {
                        connection = (HttpURLConnection) mUrl
                                .openConnection();
                    }

                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap = BitmapFactory.decodeStream(input);
                    if (myBitmap != null)
                        return true;

                } catch (IOException e) {
                    return false;
                }

                return false;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (!result && !Utility.isNullOrEmpty(fileName) && !fileName.contains("null") && (fileName.startsWith("http:") || fileName.startsWith("https:"))) {
                    picasso.load(fileName)
                            .placeholder(R.drawable.add_photo)
                            .skipMemoryCache()
                            .error(R.drawable.add_photo)
                            .resizeDimen(R.dimen.image_size,
                                    R.dimen.image_size).centerInside()
                            .into(targetImageView);
                }

                if (!Utility.isNullOrEmpty(fileName) && !fileName.contains("null") && fileName.startsWith("/mnt")) {
                    File file = new File(fileName);
                    picasso.load(file)
                            .placeholder(R.drawable.add_photo)
                            .skipMemoryCache()
                            .error(R.drawable.add_photo)
                            .resizeDimen(R.dimen.image_size,
                                    R.dimen.image_size).centerInside()
                            .into(targetImageView);
                }

                if (result) {
                    picasso.load(photoUrl)
                            .placeholder(R.drawable.add_photo)
                            .skipMemoryCache()
                            .error(R.drawable.add_photo)
                            .resizeDimen(R.dimen.image_size,
                                    R.dimen.image_size).centerInside()
                            .into(targetImageView);
                }
            }

        }.execute();

    }

    private Target targetImageView = new Target() {
        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
            if (isAdded()) {
                final Bitmap smallBitmap = decodeSampledBitmapFromResource(bitmap, getResources().getDimensionPixelSize(R.dimen.image_size), getResources().getDimensionPixelSize(R.dimen.image_size));
                if (smallBitmap != null) {

                    imageViewPhoto.setImageBitmap(smallBitmap);
                    mProgressBarImageLoad.setVisibility(View.GONE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                                if (isSDPresent) {
                                    mPhotoUrl = Environment.getExternalStorageDirectory().getPath() + "/" + "temp.png";
                                    File file = new File(mPhotoUrl);

                                    file.createNewFile();
                                    FileOutputStream ostream = new FileOutputStream(file);
                                    smallBitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
                                    ostream.close();
                                }

                            } catch (Exception e) {
                                Utility.Log("ProfileFragment -> onBitmapLoaded", e);
                            }
                        }
                    }).start();
                }
            }
        }

        @Override
        public void onBitmapFailed(Drawable drawable) {
            mProgressBarImageLoad.setVisibility(View.GONE);
        }

        @Override
        public void onPrepareLoad(Drawable drawable) {
            mProgressBarImageLoad.setVisibility(View.VISIBLE);
        }
    };

    private void LoadSocialData(User userData) {

        if (userData == null || Utility.isNullOrEmpty(userData.GooglePlusName)) {
            mTextViewGooglePlusName.setText(getResources().getString(R.string.google_plus));
            mImageViewClearGooglePlus.setVisibility(View.GONE);
        }
        if (userData != null && !Utility.isNullOrEmpty(userData.GooglePlusName) && !userData.GooglePlusName.equals("null")) {
            mTextViewGooglePlusName.setText(userData.GooglePlusName);
            mCurrentUser.GooglePlusId = userData.GooglePlusId;
            mCurrentUser.GooglePlusName = userData.GooglePlusName;
            mImageViewClearGooglePlus.setVisibility(View.VISIBLE);
        }

        if (userData == null || Utility.isNullOrEmpty(userData.LinkedInName)) {
            mTextViewLinkedInName.setText(getResources().getString(R.string.linked_in));
            mImageViewClearLinkedIn.setVisibility(View.GONE);
        }

        if (userData != null && !Utility.isNullOrEmpty(userData.LinkedInName) && !userData.LinkedInName.equals("null")) {
            mTextViewLinkedInName.setText(userData.LinkedInName);
            mCurrentUser.LinkedInId = userData.LinkedInId;
            mCurrentUser.LinkedInName = userData.LinkedInName;
            mImageViewClearLinkedIn.setVisibility(View.VISIBLE);
        }

        if (userData == null || Utility.isNullOrEmpty(userData.FacebookName)) {
            mTextViewFacebookName.setText(getResources().getString(R.string.facebook));
            mImageViewClearFacebook.setVisibility(View.GONE);
        }
        if (userData != null && !Utility.isNullOrEmpty(userData.FacebookName) && !userData.FacebookName.equals("null")) {
            mTextViewFacebookName.setText(userData.FacebookName);
            mCurrentUser.FacebookId = userData.FacebookId;
            mCurrentUser.FacebookName = userData.FacebookName;
            mImageViewClearFacebook.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoadComplete(User user) {

        if (user != null && !Utility.isNullOrEmpty(user.GooglePlusId) && !Utility.isNullOrEmpty(user.GooglePlusName)) {
            mCurrentUser.GooglePlusId = user.GooglePlusId;
            mCurrentUser.GooglePlusName = user.GooglePlusName;
        }

        if (user != null && !Utility.isNullOrEmpty(user.LinkedInId) && !Utility.isNullOrEmpty(user.LinkedInName)) {
            mCurrentUser.LinkedInId = user.LinkedInId;
            mCurrentUser.LinkedInName = user.LinkedInName;
        }

        if (user != null && !Utility.isNullOrEmpty(user.FacebookId) && !Utility.isNullOrEmpty(user.FacebookName)) {
            mCurrentUser.FacebookId = user.FacebookId;
            mCurrentUser.FacebookName = user.FacebookName;
        }

        LoadSocialData(mCurrentUser);

        mRelativeLayoutGooglePlus.setEnabled(true);
        mProgressBarGooglePlus.setVisibility(View.GONE);

        mRelativeLayoutLinkedIn.setEnabled(true);
        mProgressBarLinkedIn.setVisibility(View.GONE);

        mRelativeLayoutFacebook.setEnabled(true);
        mProgressBarFacebook.setVisibility(View.GONE);
    }

    private User MergeUserData(User user, User userFromSocial) {

        if (Utility.isNullOrEmpty(user.FirstName))
            user.FirstName = userFromSocial.FirstName;
        if (Utility.isNullOrEmpty(user.LastName))
            user.LastName = userFromSocial.LastName;
        if (Utility.isNullOrEmpty(user.Email))
            user.Email = userFromSocial.Email;
        if (Utility.isNullOrEmpty(user.Phone))
            user.Phone = userFromSocial.Phone;
        if (Utility.isNullOrEmpty(user.Title))
            user.Title = userFromSocial.Title;
        if (Utility.isNullOrEmpty(user.Company))
            user.Company = userFromSocial.Company;
        if (Utility.isNullOrEmpty(user.Site))
            user.Site = userFromSocial.Site;
        if (Utility.isNullOrEmpty(user.City))
            user.City = userFromSocial.City;
        if (Utility.isNullOrEmpty(user.State))
            user.State = userFromSocial.State;
        if (Utility.isNullOrEmpty(user.Info))
            user.Info = userFromSocial.Info;
        if (Utility.isNullOrEmpty(user.FacebookId))
            user.FacebookId = userFromSocial.FacebookId;
        if (Utility.isNullOrEmpty(user.FacebookName))
            user.FacebookName = userFromSocial.FacebookName;
        if (Utility.isNullOrEmpty(user.GooglePlusId))
            user.GooglePlusId = userFromSocial.GooglePlusId;
        if (Utility.isNullOrEmpty(user.GooglePlusName))
            user.GooglePlusName = userFromSocial.GooglePlusName;
        if (Utility.isNullOrEmpty(user.LinkedInId))
            user.LinkedInId = userFromSocial.LinkedInId;
        if (Utility.isNullOrEmpty(user.LinkedInName))
            user.LinkedInName = userFromSocial.LinkedInName;
        if (Utility.isNullOrEmpty(user.ImageUrl))
            user.ImageUrl = userFromSocial.ImageUrl;

        return user;

    }

    private void CheckEmail() {
        progressDialog.show();

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {
                try {

                    return Utility.ConnectServer(Utility.CHECK_EMAIL_URL + "?email=" + editTextEmail.getText().toString(), Utility.RequestMethodType.GET, null);
                } catch (Exception ex) {
                    Utility.Log("Error is connection to the service", ex);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(String result) {
                if (!Utility.isNullOrEmpty(result)) {
                    try {
                        JSONObject resultJsonObject = new JSONObject(result);
                        if (!resultJsonObject.has("Error")) {
                            String resultObject = resultJsonObject
                                    .getString("Result");
                            if (!Utility.isNullOrEmpty(resultObject) && !Boolean.valueOf(resultObject))
                                SaveUserProfile();
                            else
                                Toast.makeText(getActivity(), getResources().getString(R.string.email_in_already_use), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException ex) {
                        Utility.Log("Check email convert String to Json in LoginActivity", ex);
                    }
                }

                progressDialog.dismiss();
            }
        }.execute();
    }

    private void ClearPhoto() {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... voids) {
                return Utility.ConnectServer(Utility.DELETE_PHOTO_URL + "?UserToken=" + Utility.getUserSession(getActivity()).UserToken, Utility.RequestMethodType.GET, null);
            }

            @Override
            protected void onPostExecute(String s) {
                if (!Utility.isNullOrEmpty(s) && !s.equals("null")) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        if (jsonObject.has("Result")) {
                            String result = jsonObject.getString("Result");
                            if (result.equals("True")) {
                                imageViewPhoto.setImageResource(R.drawable.add_photo);
                                Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                                if (isSDPresent) {
                                    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "temp.png");
                                    if (file.exists())
                                        file.delete();
                                }
                            } else
                                Toast.makeText(getActivity(), "Cannot clear the photo", Toast.LENGTH_SHORT).show();
                        } else
                            Toast.makeText(getActivity(), "Cannot clear the photo", Toast.LENGTH_SHORT).show();

                    } catch (Exception ex) {
                        Utility.Log("ProfileFragment -> ClearPhoto", ex);
                    }
                } else
                    Toast.makeText(getActivity(), "Cannot clear the photo", Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }

    private static String formatPhoneNumber(String s) {

        int localNumberMaxLength = 7;
        int areaCodeMaxLength = 3;
        int countryCodeMaxLength = 3;
        String removerWhiteSpacePattern = "(\\w)(\\s+)([\\.,])";
        s = s.replaceAll(removerWhiteSpacePattern, "");

        StringBuffer resulsString = new StringBuffer();
        String newNumber = new String();

        // Strip all non-numbers
        for (int i = 0; i < s.length(); i++) {

            if (Character.isDigit(s.charAt(i))) {
                newNumber += (s.charAt(i));
            }
        }


        if (newNumber.length() > localNumberMaxLength + areaCodeMaxLength + countryCodeMaxLength) {
            newNumber = newNumber.substring(0, localNumberMaxLength + areaCodeMaxLength + countryCodeMaxLength);
        }

        int localNumberLength = Math.min(newNumber.length(), localNumberMaxLength);
        if (localNumberLength > 0) {
            String number = newNumber.substring(newNumber.length() - localNumberLength);
            resulsString.append(number);
            if (resulsString.length() > 3) {
                resulsString.insert(3, "-");
            }
        }

        if (newNumber.length() > localNumberMaxLength) {

            int areaCodeLength = Math.min(newNumber.length() - localNumberMaxLength, areaCodeMaxLength);

            int startPosition = newNumber.length() - localNumberLength - areaCodeLength;

            String areaCodeString = newNumber.substring(startPosition, startPosition + areaCodeLength);

            areaCodeString = String.format("(%s)", areaCodeString);

            resulsString.insert(0, areaCodeString);
        }

        if (newNumber.length() > localNumberMaxLength + areaCodeMaxLength) {

            int countryCodeLength = Math.min(newNumber.length() - localNumberMaxLength - areaCodeMaxLength, countryCodeMaxLength);

            String countryCode = newNumber.substring(0, countryCodeLength);

            countryCode = String.format("+%s", countryCode);

            resulsString.insert(0, countryCode);
        }

        return resulsString.toString();
    }

    public static Bitmap decodeSampledBitmapFromResource(Bitmap bitmap,
                                                         int reqWidth, int reqHeight) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()), null, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()), null, options);
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

}
